// components/upload/upload.js
Component({
  options: {
    styleIsolation: 'shared'
  },
  /**
   * 组件的属性列表
   */
  properties: {
    files: {
      type: Array,
      value: []
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    maxCount: 6,
    finishFiles: [],
    tipsType: '', // toptips--类型
    tipsMsg: '' // toptips--提示内容
  },

  observers: {
    "files": function (value) {
      this.setData({
        finishFiles: value.map(v => ({ url: v, cloudUrl: v }))
      })
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {

    /**
     * 选择图片
     * @param {Event} event 
     */
    bindSelect (event) {
      const paths = event.detail.tempFilePaths
      if (paths.length > 0) {
        let finishFiles = this.data.finishFiles
        paths.forEach(v => {
          finishFiles.push({
            url: v,
            loading: true
          })
          this.uploadImage(v)
        })
        this.setData({ finishFiles })
      }
    },

    /**
     * 删除图片
     * @param {Event} event 
     */
    async bindDelete (event) {
      const {index, item} = event.detail
      const finishFiles = this.data.finishFiles
      const file = finishFiles[index]
      let finish = true
      if (file.cloudUrl) {
        // 删除云端图片
        this.deleteImage(file.cloudUrl)
      }
      finishFiles.splice(index, 1)
      this.setData({ finishFiles })
      this.updateCloudFiles()
    },

    /**
     * 上传图片
     * @param {String} filePath 文件位置
     */
    uploadImage (filePath) {
      const _this = this
      return new Promise((resolve, reject) => {
        const date = new Date()
        const sn = date.getTime().toString() + Math.floor(Math.random() * 10000).toString()
        const year = date.getFullYear()
        let month = date.getMonth() + 1
        month = month >= 10 ? month : '0' + month
        const cloudPath = `image/${year}${month}/${sn}${filePath.match(/\.[^.]+?$/)[0]}`
        wx.cloud.uploadFile({
          filePath,
          cloudPath,
          success: res => {
            _this.updateFileStatus({
              url: filePath,
              cloudUrl: res.fileID,
              loading: false
            })
          },
          fail: e => {
            _this.updateFileStatus({
              url: filePath,
              loading: false,
              error: true
            })
          }
        })
      })
    },

    /**
     * 删除云端图片
     * @param {String} url 云端图片路径
     */
    deleteImage (url) {
      return new Promise((resolve, reject) => {
        wx.cloud.deleteFile({
          fileList: [url]
        }).then(res => {
          if (res.errMsg === 'ok') {
            resolve(true)
          } else {
            resolve(false)
          }
        }).catch(err => {
          resolve(false)
        })
      })
    },

    /**
     * 更新图片数据、状态
     * @param {Object} file 
     */
    updateFileStatus (file) {
      const index = this.data.finishFiles.findIndex(v => {
        return v.url === file.url
      })
      if (index >= 0) {
        this.setData({
          [`finishFiles[${index}]`]: file
        })
        this.updateCloudFiles()
      }
    },

    /**
     * 更新已上传图片列表
     */
    updateCloudFiles () {
      const cloudFiles = []
      this.data.finishFiles.forEach(v => {
        if (v.cloudUrl) {
          cloudFiles.push(v.cloudUrl)
        }
      })
      this.triggerEvent('change', { value: cloudFiles })
    }
  }
})
